﻿using System.IO;
using System.Net;

namespace NBazzinga
{
    /// <summary>
    /// Слой HTTP для запросов Баззинги
    /// </summary>
    public class Http
    {
        private readonly string useragent;
        private readonly WebProxy webProxy;

        public Http()
        {
        }

        public Http(WebProxy _webProxy)
        {
            webProxy = _webProxy;
        }

        public Http(WebProxy _webProxy, string _useragent)
        {
            webProxy = _webProxy;
            useragent = _useragent;
        }

        public string HttpPost(string uri, byte[] post, string cookie = null)
        {
            var webRequest = (HttpWebRequest) WebRequest.Create(uri);
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.UserAgent = useragent;
            webRequest.Accept = "text/html";
            webRequest.Headers.Add("Cookie", cookie);
            webRequest.Timeout = 30000;
            webRequest.ContentLength = post.Length;
            webRequest.SendChunked = true;
            webRequest.AllowWriteStreamBuffering = false;
            if (webProxy != null) webRequest.Proxy = webProxy;
            Stream os = null;
            try
            {
                os = webRequest.GetRequestStream();
                os.Write(post, 0, post.Length);
            }
            finally
            {
                if (os != null)
                {
                    os.Close();
                }
            }
            WebResponse webResponse = webRequest.GetResponse();
            using (var sr = new StreamReader(webResponse.GetResponseStream()))
            {
                return sr.ReadToEnd().Trim();
            }
        }

        public WebResponse HttpPost(string uri)
        {
            var webRequest = (HttpWebRequest) WebRequest.Create(uri);
            webRequest.Method = "POST";
            webRequest.UserAgent = useragent;
            webRequest.Accept = "text/html";
            webRequest.Timeout = 30000;
            if (webProxy != null) webRequest.Proxy = webProxy;
            webRequest.GetRequestStream();
            return webRequest.GetResponse();
        }
    }
}